package com.leilei.gateway.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lei
 * @create 2022-04-11 16:20
 * @desc
 **/
@Service
@Log4j2
public class MyRouteDefinitionService implements RouteDefinitionRepository {

    private final GatewayProperties gatewayProperties;
    private final RouteService routeService;

    public MyRouteDefinitionService(GatewayProperties gatewayProperties, RouteService routeService) {
        this.gatewayProperties = gatewayProperties;
        this.routeService = routeService;
    }

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        List<RouteDefinition> routes = Collections.synchronizedList(gatewayProperties.getRoutes());
        Set<String> routeIdSet = routes.stream().map(RouteDefinition::getId).collect(Collectors.toSet());
        log.info("进入了查询方法 共获取路由信息数量：{}", routes.size());
        log.info(JSON.toJSONString(routes));
        // 从持久化层获取自定义路由信息
        List<RouteDefinition> routeDefinitions = routeService.getRouteList()
                .stream()
                .filter(x->!routeIdSet.contains(x.getId())).collect(Collectors.toList());
        routes.addAll(routeDefinitions);
        return Flux.fromIterable(routes);
    }

    @Override
    public Mono<Void> save(Mono<RouteDefinition> route) {
        log.info("进入了新增方法");
        return Mono.empty();
    }

    @Override
    public Mono<Void> delete(Mono<String> routeId) {
        log.info("进入了修改方法");
        return Mono.empty();
    }


}
